package com.qiwenshare.file.service;
import com.qiwenshare.file.util.SessionKey;
import com.qiwenshare.file.api.SmsService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by win10 on 2020/4/24.
 */
@Service
public class SmsServiceImpl implements SmsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SmsServiceImpl.class);

    private LocalDateTime expireTime;

    /**
     * 验证码5分钟有效
     */
    private Integer exprieSeconds = 300;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Override
    public String generateCode() {
        String code = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            int r = random.nextInt(10); //每次随机出一个数字（0-9）
            code = code + r;  //把每次随机出的数字拼在一起
        }
        LOGGER.info(code);
        this.expireTime = LocalDateTime.now().plusSeconds(exprieSeconds);
        return code;
    }

    @Override
    public Boolean requestTimeValid()  {
        boolean valid = false;
        if(httpServletRequest.getSession().getAttribute(SessionKey.SendTime)!=null ){   //session有发送时间记录
            long sp =System.currentTimeMillis() - (long)httpServletRequest.getSession().getAttribute(SessionKey.SendTime);
            if(sp>60*1000){//间隔上一次发送超过1分钟 可发送验证码
                valid = true;
            }else{
                //提醒用户已发送验证码
                valid = false;
            }
        }
        else{
            //session有效期内没有发送过
            valid = true;
        }
        return valid;
    }

    @Override
    public Boolean validSMSCode(String smscode,String SessionKey)  {
        if(httpServletRequest.getSession().getAttribute(SessionKey)==null){
            return false;
        }
        Boolean valid = StringUtils.equalsIgnoreCase(smscode,(String) httpServletRequest.getSession().getAttribute(SessionKey));
        if(LocalDateTime.now().isAfter(expireTime)){
            return false;
        }
        return valid;
    }

    public void clearSMSCode(String page){
        httpServletRequest.getSession().removeAttribute(page);
    }

    @Override
    public void loginFailRecord() {
        httpServletRequest.getSession().setAttribute(SessionKey.LoginTime,System.currentTimeMillis());
    }

    @Override
    public Boolean loginTimeValid()  {
        Boolean valid = false;
        if(httpServletRequest.getSession().getAttribute(SessionKey.LoginTime)!=null ){ //有登录失败记录
            long sp =System.currentTimeMillis() - (long)httpServletRequest.getSession().getAttribute(SessionKey.LoginTime);
            if(sp>2*1000){//登录间隔超过2秒 正常登录
                valid = true;
            }else{
                //提醒用户操作太频繁
                valid = false;
            }
        }
        else{
            //session有效期内没有登录过
            valid = true;
        }
        return valid;
    }

    @Override
    public String sendSMSCode(String telphone,String page)  {
        String code = generateCode();
        return getString(telphone, page,code);
    }

    public String sendSMSCode(String telphone,String page,String code)  {
        return getString(telphone, page, code);
    }

    private String getString(String telphone, String page,String code)  {
        String result = null;


        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                List<BasicNameValuePair> formparams = new ArrayList<>();
                formparams.add(new BasicNameValuePair("Account","15823536977"));
                formparams.add(new BasicNameValuePair("Pwd","30dd57f1f00e5d7206cea473d"));//登录后台 首页显示
                formparams.add(new BasicNameValuePair("Content",code));
                formparams.add(new BasicNameValuePair("Mobile",telphone));
                formparams.add(new BasicNameValuePair("SignId","255401"));//登录后台 添加签名获取id
                formparams.add(new BasicNameValuePair("TemplateId","141761"));
                HttpPost httpPost = new HttpPost("http://api.feige.ee/SmsService/Template");
                httpPost.setEntity(new UrlEncodedFormEntity(formparams,"UTF-8"));
                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity);
                httpServletRequest.getSession().setAttribute(page,code);
//                httpServletRequest.getSession().setAttribute(SessionKey.Telphone,telphone);
//                httpServletRequest.getSession().setAttribute(SessionKey.Page,page);
                httpServletRequest.getSession().setAttribute(SessionKey.SendTime,System.currentTimeMillis());
                LOGGER.info(result);
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return result;
    }

}
